//
//  ModuleFirstTopicDetailViewController.m
//  艾听歌
//
//  Created by dllo on 16/5/29.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ModuleFirstTopicDetailViewController.h"

#import "ModuleFirst_TopicDetailsBigModel.h"
#import "ModuleFirst_TopicDetailsRowModel.h"

#import "TravelsTopicDetailsTableViewCell.h"

#import "Height.h"


#define VIEWW self.view.frame.size.width
#define VIEWH self.view.frame.size.height


static NSString *const tableViewCell = @"reuse";

@interface ModuleFirstTopicDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *myTableView;

@property (nonatomic, assign) BOOL isUpLoading;//标记上拉操作还是下拉操作,yes是上拉

@property (nonatomic, assign)NSInteger nextpage;//记录下一页


@property (nonatomic, strong) NSMutableArray *allDataArray;


@end

@implementation ModuleFirstTopicDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor whiteColor];
    self.view.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff, 0x9c9c9c);
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorPickerWithRGB(0xFF6EB4, 0x9C9C9C);

    
    NSLog(@"111111111111111%@", self.cellModel.idd);
   
    
    //调整坐标
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, VIEWW, VIEWH - 66) style:UITableViewStylePlain];
//    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff, 0x9c9c9c);
    [self.view addSubview:self.myTableView];
    
    //消除分割线
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    //成为代理人
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    
    
    //tableView注册
    [self.myTableView registerClass:[TravelsTopicDetailsTableViewCell class] forCellReuseIdentifier:tableViewCell];
    
    
    
    //导航栏左侧返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"BackButton_1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftBackButton)];
    
//    self.isUpLoading = NO;
    self.allDataArray = [NSMutableArray array];
    
    //2.集成上拉下拉功能
    [self addHeader];
    [self addFooter];
//    [self GETDataAFNetworkingData:self.nextpage];
    
    
}


#pragma  mark --下拉刷新
- (void)addHeader{
    
    __block ModuleFirstTopicDetailViewController *root = self;
     //添加下拉刷新头部控件
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //进入刷新状态就会回调这个block
        root.nextpage = 1;//记录页码的
        root.isUpLoading = NO;//标记为下拉操作
        [root getAFNetworkingData:root.nextpage];//请求数据
        
        
    }];
    
 #pragma mark --自动刷新(--进入程序就下拉刷新)
    [self.myTableView.mj_header beginRefreshing];
    
}



#pragma mark -- 上拉加载更多
- (void)addFooter{
    
    __block ModuleFirstTopicDetailViewController *root = self;
    
    //添加上拉刷新尾部控件
self.myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
    
    
    //进入刷新状态就会回调这个Block
    
    root.isUpLoading = YES;//标记为上拉操作
    root.nextpage++;
    [root getAFNetworkingData:root.nextpage];
    [self.myTableView reloadData];
    
}];
    

}



//网络请求数据
- (void)getAFNetworkingData:(NSInteger)nextCursor{
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //创建一个管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.securityPolicy setAllowInvalidCertificates:YES];
    [manager.securityPolicy setValidatesDomainName:NO];
    //识别各种类型的网址
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];

    NSString *string = [NSString stringWithFormat:@"https://chanyouji.com/api/articles/%ld.json?page=%ld", [self.cellModel.idd integerValue],  nextCursor] ;
    [manager GET:string parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //******
        [netWorkManager stopMonitoring];
        
        if (self.isUpLoading == NO) {
            
            //说明是下拉,就要清空数组中的数据
            [self.allDataArray removeAllObjects];
        }
        
        ModuleFirst_TopicDetailsBigModel *bigModel = [[ModuleFirst_TopicDetailsBigModel alloc]init];
        [bigModel setValuesForKeysWithDictionary:responseObject];
        
        if (nextCursor == 1) {
        
        NSMutableArray *article_sections = bigModel.article_sections;
        for (ModuleFirst_TopicDetailsRowModel *rowModel in article_sections) {
    
//            NSLog(@"%@", rowModel.descriptions);
            
            [self.allDataArray addObject:rowModel];
            
        }
  }
    
        [self.myTableView.mj_footer endRefreshing];
        [self.myTableView.mj_header endRefreshing];
        
        [self.myTableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error====%@",error);
        
        
    }]; 
    
    
}





//必须做的
//显示每个cell的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TravelsTopicDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableViewCell forIndexPath:indexPath];
    
    cell.contentView.layer.cornerRadius = 6;
    cell.contentView.layer.masksToBounds = YES;


    cell.cellRowModel = [self.allDataArray objectAtIndex:indexPath.row];
    //消除cell被点击时的灰色背景
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    return cell;
    
}


//每个分区里有多少个cell

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return self.allDataArray.count;
}



//选做的
//每个cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ModuleFirst_TopicDetailsRowModel *model = [self.allDataArray objectAtIndex:indexPath.row];
    
     CGFloat titleLabelHeight = [Height getLabelHeightWithString:model.title widthNowLabel:VIEWW - 20 fontSize:25 options:NSStringDrawingUsesLineFragmentOrigin];
    
    CGFloat imageHeight = [Height getHeightImageWithHeight:model.image_height withWidth:model.image_width widthNowImage:VIEWW - 20];
    
    CGFloat descriptionLabelHeight = [Height getLabelHeightWithString:model.descriptions widthNowLabel:VIEWW - 20 fontSize:15 options:NSStringDrawingUsesLineFragmentOrigin];

    
    return titleLabelHeight + imageHeight + descriptionLabelHeight + 20;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(TravelsTopicDetailsTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    CATransform3D rotation;//3D旋转
    // 平移  它是把参数作为一个弧度，然后把弧度再转换为角度来处理，
    rotation = CATransform3DMakeTranslation(0 ,50 ,20);
    // 缩放
    rotation = CATransform3DScale(rotation, 0.9, .9, 1);
    
    rotation.m34 = 1.0/ -600;
    
    cell.layer.shadowColor = [[UIColor blackColor] CGColor];
    cell.layer.shadowOffset = CGSizeMake(10, 10);
    cell.alpha = 0;
    
    cell.layer.transform = rotation;
    
    [UIView beginAnimations:@"rotation" context:NULL];
    //旋转时间
    [UIView setAnimationDuration:0.9];
    cell.layer.transform = CATransform3DIdentity;
    cell.alpha = 1;
    cell.layer.shadowOffset = CGSizeMake(0, 0);
    [UIView commitAnimations];
//
//    CATransition *at = [CATransition animation];
//    // 设置动画类型
//    at.type = @"pageCurl";
//    // 设置动画时长
//    at.duration = 2;
//    at.subtype = kCATransitionFromRight;
////    UIButton *button = indexPath;
//    
//    [cell.layer addAnimation:at forKey:@"layerAnimation"];
//    
    

    
    
    
}


//导航栏左边返回按钮
- (void) leftBackButton{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
    
}


@end
